﻿
//using OpenQA.Selenium;
//using OpenQA.Selenium.Chrome;
//using OpenQA.Selenium.Chromium;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chromium;
using PuppeteerSharp;
using PuppeteerSharp.Media;
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace LVYAN.Utils
{
    public class ImageService
    {
        public static string ImageBitmapToBase64(Bitmap bitmap)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;
                // 将Bitmap对象保存到MemoryStream中  
                bitmap.Save(memoryStream, format);
                byte[] imageBytes = memoryStream.ToArray();
                // 将字节数组转换为Base64字符串  
                string base64String = Convert.ToBase64String(imageBytes);
                // 返回Base64字符串  
                return $"data:image/{format.ToString()};base64,{base64String}";
            }
        }
        public static string ImageUrlToBase64(string imagePath)
        {
            using (Image image = Image.FromFile(imagePath))
            {
                using (MemoryStream m = new MemoryStream())
                {
                    // 将图片保存为PNG格式到内存流中  
                    // 注意：这里你也可以使用其他格式，比如Jpeg，通过调用image.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);  
                    image.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] imageBytes = m.ToArray();
                    // 将字节数组转换为Base64字符串  
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
            }
        }
        public static Bitmap CropImageContact(Bitmap source, Rectangle section)
        {
            section.Width = 30;
            section.Height = 30;
            var bitmap = new Bitmap(section.Width, section.Height);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            }
            return bitmap;
        }
        public static Bitmap CropImage(Bitmap source, Rectangle section)
        {
            section.Width = 36;
            section.Height = 36;
            var bitmap = new Bitmap(section.Width, section.Height);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            }
            return bitmap;
        }
        public static Bitmap CropImageHuiHua(Bitmap source, Rectangle section)
        {
            section.Width = 35;
            section.Height = 35;
            var bitmap = new Bitmap(section.Width, section.Height);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            }
            return bitmap;
        }
        public static Bitmap Img(Bitmap source, Rectangle section)
        {
            var bitmap = new Bitmap(section.Width, section.Height);
            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
            }
            return bitmap;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Name"></param>
        /// <param name="Width">350</param>
        /// <param name="Height"> 718</param>
        /// <returns></returns>
        public static string UrlToImg(string Url, string Name, int Width, int Height)
        {
            ChromeOptions options = new ChromeOptions();
            // 如果需要无头模式（无界面），可以添加以下行  
            options.AddArguments("headless");
            options.EnableMobileEmulation(new ChromiumMobileEmulationDeviceSettings() { Width = Width, Height = Height, UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1" });
            //options.EnableMobileEmulation("iPhone XR");
            IWebDriver driver = new ChromeDriver(options);
            string FilePath = string.Empty;
            try
            {
                driver.Navigate().GoToUrl(Url);
                // 等待页面加载完成（这里使用了简单的等待，实际中可能需要更复杂的等待策略）  
                Thread.Sleep(5000); // 等待5秒  
                // 截取屏幕截图  
                Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
                var ImgPath = $"Data/Html/{DateTime.Now.ToString("HHmmss")}{Name}.png";
                FilePath = Path.GetFullPath(ImgPath);
                string directoryName = Path.GetDirectoryName(FilePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                screenshot.SaveAsFile(FilePath);
            }
            finally
            {
                driver.Quit();
            }
            return FilePath;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url">页面地址</param>
        /// <param name="Name">新的名称</param>
        /// <param name="QuerySelector">需要截图的区域</param>
        /// <param name="ExecutablePath">谷歌的安装位置</param>
        /// <returns></returns>
        public static string UrlToImg(string Url, string Name, string QuerySelector, string ExecutablePath)
        {
            // 目标URL

            // 本地保存路径（确保目录存在）
            string FilePath = string.Empty;
            var ImgPath = $"Data/Html/{DateTime.Now.ToString("HHmmss")}{Name}.png";
            FilePath = Path.GetFullPath(ImgPath);
            string directoryName = Path.GetDirectoryName(FilePath);
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            try
            {

                var run = Task.Run(async () =>
                {
                    // 启动浏览器
                    Console.WriteLine("正在启动浏览器...");
                    await using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
                    {
                        Headless = true,
                        ExecutablePath = ExecutablePath,
                        Args = new[] { "--no-sandbox" }
                    }))
                    {
                        // 创建新页面
                        Console.WriteLine("正在加载页面...");
                        await using (var page = await browser.NewPageAsync())
                        {
                            // 设置视口大小
                            await page.SetViewportAsync(new ViewPortOptions
                            {
                                Width = 1920,
                                Height = 1080,
                                DeviceScaleFactor = 3
                            });
                            // 导航到目标URL
                            await page.GoToAsync(Url, WaitUntilNavigation.Networkidle0);
                            // 额外检查DOM中的图片是否全部加载完成
                            await page.WaitForFunctionAsync(@"() => {
    const images = Array.from(document.images);
    if (images.length === 0) return true;
    
    // 检查所有图片是否已完成加载（complete属性）
    const allLoaded = images.every(img => img.complete);
    
    // 检查所有图片是否可见且已渲染
    const allRendered = images.every(img => {
        const rect = img.getBoundingClientRect();
        return img.naturalWidth > 0 && rect.width > 0 && rect.height > 0;
    });
    
    return allLoaded && allRendered;
}", new WaitForFunctionOptions { Timeout = 30000 });

                            // 等待页面元素加载（根据实际页面调整选择器）
                            Console.WriteLine("等待页面元素加载...");
                            await page.WaitForSelectorAsync($".{QuerySelector}", new WaitForSelectorOptions {
                                Timeout = 10000,
                                Visible = true 
                            });
                            // 强制高质量渲染
                            await page.EvaluateExpressionAsync(@"
                document.body.style.textRendering = 'optimizeLegibility';
                document.body.style.webkitFontSmoothing = 'antialiased';
            ");
                            // 1. 截取整个页面并保存
                            //Console.WriteLine("正在截取完整页面...");
                            //await page.ScreenshotAsync(fullPagePath, new ScreenshotOptions
                            //{
                            //    FullPage = true,
                            //    Type = ScreenshotType.Png
                            //});
                            // 2. 截取特定元素并保存
                            Console.WriteLine("正在截取服务元素区域...");
                            var element = await page.QuerySelectorAsync($".{QuerySelector}");
                            if (element != null)
                            {//product-listing-container

                                await element.ScreenshotAsync(FilePath);
                            }
                            else
                            {
                                Console.WriteLine("未找到指定的服务元素");
                            }

                            //Console.WriteLine($"截图已保存至: {saveDirectory}");
                            //Console.WriteLine($"完整页面: {fullPagePath}");
                            Console.WriteLine($"元素截图: {FilePath}");
                        }
                    }
                });
                run.Wait();

            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }

            return FilePath;
        }
    }
}